<!--
 * @Author: your name
 * @Date: 2021-04-10 15:59:58
 * @LastEditTime: 2021-06-01 08:58:14
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ws-shop\src\views\login.vue
-->
<template>
  <div class="login">
    <div class="login-main">
      <h2>用户登录</h2>
      <van-form>
        <van-field
          autocomplete="off"
          v-model="username"
          name="账号"
          label="账号"
          placeholder="账号"
          :rules="[{ required: true, message: '请填写账号' }, {pattern:/^\w{8,}$/}]"
          clickable
          :value="username"
        />
        <van-field
          autocomplete="off"
          v-model="password"
          type="password"
          name="密码"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }, {pattern:/^\w{6,}$/}]"
          clickable
          :value="password"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit" @click="login">
            登录
          </van-button>
        </div>
      </van-form>
      <div class="toRegister">
        <p>
          <router-link to="/register">没有账号？请注册</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { Form, Toast } from 'vant'

Vue.use(Form, Toast)

export default {
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    login () {
      this.$http.getSessions({
        username: this.username,
        password: this.password
      }).then(res => {
        if (res.valid) {
          Toast.success('登录成功')
          sessionStorage.setItem('user', res.userInfo.nickname)
          console.log(res.userInfo.nickname)
          setTimeout(() => {
            this.$router.push({
              path: '/mine'
            })
          }, 2000)
          document.cookie = 'username:' + this.username
        } else {
          Toast.fail('账户或密码输入有误 请确认后再试！')
        }
      })
      if (this.username.trim() === '') {
        return
      }
      if (this.password.trim() === '') {
        return
      }
      if (
        !this.username.match(/^[1][3,4,5,6,7,8][0-9]{9}$/) && !this.password.match(/^\w{6,}$/)
      ) {
        return false
      }
    }
  }
}
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
}
html,
body,
.login {
  height: 100%;
}
.login {
  display: flex;
  flex-direction: column;
}
.login-main {
  flex: 1;
  padding: 150px 0;
  text-align: center;
  h2{
    line-height: 2;
    color: #1989fa;
  }
}
.toRegister {
  p {
    line-height: 2;
    color: blue;
    font-size: 12px;
  }
}
</style>
